/* =================================================
 * Package:			dk.iha.toksEditor
 * File:			FavoritePatient.java
 * Description:		This is the activity for which
 * 					is responsible for showing the
 * 					patient history data.
 * 
 * Responsible
 * =================================================
 * Name:			Bjarke Jensen
 * Study number:	09676
 */

package dk.iha.toksEditor;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

public class History extends Activity {
	
	private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
	private XYMultipleSeriesRenderer mRenderer;
	private GraphicalView mChartView;
	private LinearLayout layout;
	private User mUser; 
	private ArrayList<TOKS> mTOKS;
	private DataBaseConnection dbc;
	private Patient mPatient;
	private String[] items;
	private Boolean cancel = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.history_view);	
		mUser = new User(this);
		asynch task = new  asynch();
		task.execute("");
		
	}
	
	@Override
	protected void onResume() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		if(prefs.getBoolean("checkboxPref", false))
		{
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		
		else
		{
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		super.onResume();
	}
private void createCalendar() {
	if(mRenderer == null)
	{
		mRenderer = new XYMultipleSeriesRenderer();
		mRenderer.setApplyBackgroundColor(true);
	    mRenderer.setBackgroundColor(Color.argb(100, 196, 196, 196));
	    mRenderer.setMarginsColor(Color.argb(255, 245, 253, 255));
	    mRenderer.setYLabelsColor(0,Color.argb(255, 0, 0, 0));
	    mRenderer.setXLabelsColor(Color.argb(255, 0, 0, 0));
	    mRenderer.setAxisTitleTextSize(25);
	    mRenderer.setChartTitleTextSize(20);
	    mRenderer.setLabelsTextSize(15);
	    mRenderer.setLegendTextSize(15);
	    mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
	    mRenderer.setZoomButtonsVisible(true);
	    mRenderer.setPointSize(10);
	    mRenderer.setShowGridY(true);
	    mRenderer.setShowGridX(true);
	    mRenderer.setLegendTextSize(25);
	    mRenderer.setPanEnabled(true,true);
	    
	    mChartView = ChartFactory.getTimeChartView(this, mDataset, mRenderer,null);
	    

	    layout = (LinearLayout) findViewById(R.id.chart);
	    
		layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
		          LayoutParams.FILL_PARENT));
	}
    mChartView.repaint();	
}

protected Dialog onCreateDialog(int id) {
	items = getResources().getStringArray(R.array.historyViewGraphSelect);
	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	builder.setTitle(getString(R.string.HistoryViewPickData));
	builder.setOnCancelListener(new OnCancelListener() {
		@Override
		public void onCancel(DialogInterface dialog) {
			dialog.dismiss();
		}
	});
	builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int item) {
	        changeSeries(item);
	        dialog.dismiss();
	    }
	});
	AlertDialog alert = builder.create();
	return alert;
}

private void changeSeries(Integer item)
{
	if(mTOKS.size() != 0)
	{
	if(mDataset.getSeriesCount() != 0)
	{
		
		mDataset.removeSeries(0);
	}
	TimeSeries series = new TimeSeries(items[item]);
	
	switch (item) {
	case 0:
	    for (Iterator<TOKS> toks = mTOKS.iterator(); toks.hasNext();) {
	    	TOKS t = toks.next();
	    	series.add(t.getDate(),t.getHeartRate());
		}
		break;
	case 1:
	    for (Iterator<TOKS> toks = mTOKS.iterator(); toks.hasNext();) {
	    	TOKS t = toks.next();
	    	series.add(t.getDate(),t.getTemperature());
		}
		break;
		
	case 2:
	    for (Iterator<TOKS> toks = mTOKS.iterator(); toks.hasNext();) {
	    	TOKS t = toks.next();
	    	series.add(t.getDate(),t.getOxygenLitersPerMinute());
		}
		break;
		
	case 3:
	    for (Iterator<TOKS> toks = mTOKS.iterator(); toks.hasNext();) {
	    	TOKS t = toks.next();
	    	series.add(t.getDate(),t.getRespirationFrequency());
		}
		break;
		
	case 4:
	    for (Iterator<TOKS> toks = mTOKS.iterator(); toks.hasNext();) {
	    	TOKS t = toks.next();
	    	series.add(t.getDate(),t.getSaturation());
		}
		break;
		
	case 5:
	    for (Iterator<TOKS> toks = mTOKS.iterator(); toks.hasNext();) {
	    	TOKS t = toks.next();
	    	series.add(t.getDate(),t.getBloodPressureSystolic());
		}
		break;
	case 6:
	    for (Iterator<TOKS> toks = mTOKS.iterator(); toks.hasNext();) {
	    	TOKS t = toks.next();
	    	series.add(t.getDate(),t.getBloodPressureDiastolic());
		}
		break;
	case 7:
	    for (Iterator<TOKS> toks = mTOKS.iterator(); toks.hasNext();) {
	    	TOKS t = toks.next();
	    	series.add(t.getDate(),t.getTotalScore());
		}
		break;

	default:
		break;
	}
    
    mDataset.addSeries(series);
    
    XYSeriesRenderer renderer = new XYSeriesRenderer();
    mRenderer.addSeriesRenderer(renderer);
    renderer.setPointStyle(PointStyle.CIRCLE);
    renderer.setFillPoints(true);
    mRenderer.setClickEnabled(true);
    mRenderer.setSelectableBuffer(50);
    mChartView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
          if (seriesSelection != null) {
      		Date date = new Date((long)seriesSelection.getXValue());
      		
            Toast.makeText(
                History.this,"\"" + DateFormat.format("MM/dd/yy kk:mm",date) +"\": " + seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
          }
        }
      });
    mChartView.repaint();
	}
}


@Override
public boolean onPrepareOptionsMenu(Menu menu) 
{
	showDialog(1);
    return true;
}

private class asynch extends AsyncTask<String, Integer, Boolean>
{
	private ProgressDialog mpd;
	
	@Override
	protected void onPreExecute() {
		mpd = ProgressDialog.show(History.this, getString(R.string.HistoryViewProgressTitle), getString(R.string.HistoryViewProgressDisc), true, true);	
		mpd.setOnCancelListener(new OnCancelListener() {
		
			@Override
			public void onCancel(DialogInterface dialog) {
				Intent intent = new Intent();
				setResult(RESULT_CANCELED, intent);
				cancel = true;
				finish();
			}
		});
		super.onPreExecute();
	}
	
	@Override
	protected Boolean doInBackground(String... params) {
		dbc = new DataBaseConnection(mUser);
		
		mPatient = (Patient) getIntent().getSerializableExtra("patient");
		
		mTOKS = dbc.getTOKSHistory(mPatient, 100);
		return null;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		if(!cancel)
		{
		mpd.dismiss();
		showDialog(1);
		
		createCalendar();
		}
		super.onPostExecute(result);
	}
	
}

}
